#include "qtgl.h"
#include <iostream>
#include <qtimer.h>
#include <Qscreen>
using namespace std;
QTGL::QTGL(QScreen *screen)
    : QWindow(screen)
{

	setSurfaceType(OpenGLSurface);
	QSurfaceFormat format;
	format.setDepthBufferSize(24);
	format.setMajorVersion(4);
    format.setMinorVersion(1);
	format.setSamples(4);
	format.setProfile(QSurfaceFormat::CoreProfile);
	setFormat(format);
    setFlags(flags()|Qt::WindowFullscreenButtonHint);
	create();

	_ctx = new QOpenGLContext();
	_ctx->setFormat(format);
	_ctx->create();
	_ctx->makeCurrent(this);
    _func = (QOpenGLFunctions *)_ctx->versionFunctions();
	if(!_func){
		exit(1);
	}
	_func->initializeOpenGLFunctions();
	const GLubyte * ver = glGetString(GL_VERSION);

    cout<<ver<<endl;
	_scene = new Scene();
	_scene->setContext(_ctx);
	_scene->setFuncSet(_func);
	initializeGl();

	connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeGl()));
    connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeGl()));

    if(screen){
        QRect rect = screen->geometry();
        resize(rect.width(), rect.height());
        setPosition(rect.x(),rect.y());
    }else  resize(800,600);

	QTimer *timer = new QTimer(this);
	timer->setSingleShot(true);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateScene()));
    timer->start(16);

	_ctx->makeCurrent(this);

	_rotate_status = false;
}

QTGL::~QTGL()
{
	delete _scene;
}

void QTGL::initializeGl(){
	_ctx->makeCurrent(this);
	_scene->init();
}

void QTGL::paintGl(){
	_ctx->makeCurrent(this);
	_scene->render();
	_ctx->swapBuffers(this);
}

void QTGL::resizeGl(){
	_ctx->makeCurrent(this);
	_scene->resize(width(), height());
    paintGl();
}

void QTGL::updateScene()
{
   
    paintGl();
}

void QTGL::keyPressEvent(QKeyEvent *ev){
	switch(ev->key()){
	case Qt::Key_Up:
		_scene->strafe_ud(0.1);
		break;
	case Qt::Key_Down:
		_scene->strafe_ud(-0.1);
		break;
	case Qt::Key_Left:
		_scene->strafe_lr(0.1);
		break;
	case Qt::Key_Right:
		_scene->strafe_lr(-0.1);
		break;
	}
	updateScene();
}

void QTGL::mousePressEvent(QMouseEvent *ev){
	_rotate_status = true;
	_mouse_x = ev->x();
	_mouse_y = ev->y();
}

void QTGL::mouseReleaseEvent(QMouseEvent *ev){
	_rotate_status = false;
}

void QTGL::mouseMoveEvent(QMouseEvent *ev){
	if(!_rotate_status) return;
	int _x = ev->x();
	int _y = ev->y();

	_scene->rotate_ud(_y - _mouse_y);
	_scene->rotate_lr(_x - _mouse_x);

	_mouse_x = _x;
	_mouse_y = _y;
	updateScene();
}

void QTGL::wheelEvent(QWheelEvent *e){
    _scene->zoom((double)e->pixelDelta().y()/2.0);
    updateScene();
}

